<template>
  <!-- <el-tabs
    class="message-tab"
    v-model="activeName"
    v-loading="loading"
  >
    <template v-for="tab in tabData">
      <el-tab-pane
        v-if="tab.isShow"
        :label="tab.label"
        :name="tab.name"
        :key="tab.name"
        lazy
      >
        <component
          :ref="tab.name"
          :is="tab.name"
          @getListByModule="getListByModule"
        ></component>
      </el-tab-pane>
    </template>
  </el-tabs> -->
  <div class="message-tab-box">
    <div class="message-tab-header">
      <template v-for="(tab, index) in tabData">
        <div :class="['message-tab-header__item', activeIndex === index ? 'active' : null]"
          v-if="tab.isShow"
          :key="index"
          @click="handleTabClick(tab, index)">
          {{tab.label}}
        </div>
      </template>
    </div>
    <div class="message-tab-main">
        <component
          :ref="activeName"
          :is="activeName"
          :key="activeModule"
          :active-module="activeModule"
          :projectTypeId="projectTypeId"
          @getListByModule="getListByModule"/>
    </div>
  </div>
</template>

<script>
// tab-客服中心
import customerServiceMessage from './tab/customerServiceMessage';
// tab-工单中心
import orderMessage from './tab/orderMessage';

// tab-项目管理
import projectMessage from './tab/projectMessage';

// tab-日报消息 
import reportMessage from './tab/reportMessage';
// tab-通用消息
import universalMessage from './tab/universalMessage';
// tab-通用消息
import messageRuleSettings from './tab/messageRuleSettings';
// tab-paas消息
import paasMessage from './tab/paasMessage';
// tab-门户商城消息
import portalMallMessage from './tab/portalMallMessage';
// tab-智能计划消息
import smartPlanMessage from './tab/smartPlanMessage';


// tab展示数据
import tabData from '../modal/tabData';

// 接口
import * as Message from '@src/api/Message';
import * as PaasApi from '@src/api/PassApi';

import { isBasicEdition } from '@shb-lib/version'
import querystring from '@src/util/querystring2'
import { getRootWindow } from '@src/util/dom';
/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'
// i18n
import i18n from '@src/locales';

export default {
  name:'message-tab',
  mixins: [VersionControlTaskMixin],
  components:{
    customerServiceMessage,
    orderMessage,
    reportMessage,
    universalMessage,
    paasMessage,
    messageRuleSettings,
    portalMallMessage,
    smartPlanMessage,
    projectMessage
  },


  data(){
    return{
      loading:false,
      activeName:'',
      activeIndex: 0,
      tabData,
      activeModule:'',
      projectTypeId:'',
    }
  },

  props:{
    value:{
      type:Boolean,
      required:true
    }
  },

  computed: {
    getGrayPass() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.shbPaas || false
    },
    getGrayTrain() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.TRAINING || false
    },
    getGraySmartPlan() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.SMART_PLAN || false
    },
    getGrayProject() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.PROJECT_MANAGE || false
    }
  },

  async mounted(){
    let activeIndex = 1
    this.tabData.forEach(item=>{
      // 非基础版才展示客服中心、智能报告,shbEdition=5为基础版
      if(!isBasicEdition()){
        if(item.module === 'event'){
          item.isShow = true
        }else if(item.module === 'daily'){
          item.isShow = true
        }
        activeIndex = 0
      }
      if(item.module === 'task'){
        item.isShow = this._isShowTaskModule
      }else if (this.getGrayProject && item.module === 'project') {
        // 项目管理灰度
        item.isShow = true
      }else if(this.getGrayTrain && item.module === 'course'){
        // 培训管理
        item.isShow = true
      } else if(this.getGraySmartPlan && item.module === 'smartPlan'){
        // 智能计划
        item.isShow = true
      }
    })
    
    
    
    
    if(this.getGrayPass) {
      await this.fetchPaasAppList()
    }

    const searchParams = window.location.search || ''
    const searchParamsObj = querystring.parseParams(searchParams)
    const { appId, projectTypeId, defaultModule = '' } = searchParamsObj || {}
    this.projectTypeId = projectTypeId || ''

    const lastIndex = this.tabData.length - 1
    if( appId ){
      return this.handleTabClick(this.tabData[lastIndex], lastIndex, searchParamsObj.formId)
    }
    if (projectTypeId) {
      const projectIndex = this.tabData.findIndex(item=> item.name === 'projectMessage')
      if(projectIndex > -1) {
        return this.handleTabClick(this.tabData[projectIndex], projectIndex, searchParamsObj.projectTypeId)
      }
    }

    // 默认选中的模块
    if(defaultModule) {
      const defaultIndex = this.tabData.findIndex(item=> item.module === defaultModule)
      return this.handleTabClick(this.tabData[defaultIndex], defaultIndex)
    }

    const { name, module:moduleName } = this.tabData[activeIndex]
    this.activeName = name
    this.activeModule = moduleName
    this.activeIndex = activeIndex
  },

  methods:{
    /**
     * 描述 菜单的tab点击事件
     * @date 2022-09-06
     * @param {any} tab tab的item数据结构
     * @param {any} index 菜单列表的数组下标
     * @returns {any}
     */
    handleTabClick(tab, index, formId = '') {
      this.activeName = tab.name
      this.activeModule = tab.module
      this.activeIndex = index
      // 判断是否是paas应用进行子应用的请求数据结构（）
      this.$nextTick(()=> tab.appId && this.$refs[tab.name].fetchAppFormList(formId))
    },

    /**
     * 描述 获取当前租户下的paas应用列表
     * @date 2022-09-06
     * @returns {any}
     */
    fetchPaasAppList() {
      const pass = [
        {
          isShow:true,
          label:i18n.t('trigger.passApplication'),
          name: 'paasMessage',
          appId: Date.now().toString()
        }
        ]
        // 注释防止后面改需求 
        // const rs = await PaasApi.getAppList({})
        // 重组数据结构 跟现在的tab列表对应 fromTemplateSimple下面的表单列表
        // const appList = rs.data.filter(item => item?.fromTemplateSimple?.length > 0).map(item => {
        //   return  {
        //     label: item.name,
        //     name: 'paasMessage',
        //     isShow:true,
        //     permissionKey: 'isShowConversation',
        //     module: 'paas',
        //     appId: item.appId
        //   }
        // })
        this.tabData = [...this.tabData,...pass]
    },

    // 获取列表数据，子组件也会调用
    async getListByModule(name, module) {
      try {
        this.loading = true;

        const { status, data = [], message } = await Message.getListByModule({module});

        this.switchData(data, name);

        this.loading = false;

        if (status != 0) return this.$message.warning(message);

      } catch (error) {
        this.loading = false;
        console.log(error);
      }
    },

    // 将接口请求过来的数据，赋值给this.sendDataList和this.subscribeDataList
    switchData(data, name){
      // 发送规则列表数据
      let sendDataList = []
      // 订阅通知列表数据
      let subscribeDataList = []

      data.map(item => {
        const { messageTypeName } = item
        if(messageTypeName?.toLowerCase().startsWith('sub')){
          subscribeDataList.push(item)
        }else{
          sendDataList.push(item)
        }
      })

      // 调用对应的子组件，更新数据
      // this.$refs[name]?.[0].updateList({
      //   sendDataList,
      //   subscribeDataList
      // })

      //重写tab后的版本
      this.$refs[name]?.updateList({
        sendDataList,
        subscribeDataList
      })

    }
  }
}
</script>

<style lang="scss" scoped>
.message-tab{
    ::v-deep{
        .el-tabs__header{
            margin-bottom:12px;
        }
        .el-tabs__nav-scroll{
            padding-left:17px;
        }
        .el-tabs__nav-wrap::after{
            background-color: #E3E7ED;
        }
        .el-tabs__item{
            height:44px;
            line-height:44px;
        }
    }
}
.message-tab-box{
  flex: 1;
  display: flex;
  justify-content: flex-start;
  .message-tab-header{
    width: 184px;
    box-sizing: border-box;
    border-right: 1px solid #E8E8E8;
    flex-shrink: 0;
    overflow-y: auto;
    &__item{
      padding: 4px 0 4px 16px;
      font-weight: 400;
      color: #262626;
      line-height: 24px;
      border-radius: 4px;
      margin-right: 12px;
      cursor: default;
      transition: all 0.15s ease-in;
      &:not(:first-child) {
        margin-top: 4px;
      }
      &:hover{
        background: rgba(0,0,0,0.04);
      }
      &.active {
        background: $color-primary-light-1;
        color: $color-primary-light-6;
      }
    }
  }
  .message-tab-main{
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
    padding-left: 12px;
    /* display: flex; */
    section {
      /* flex: 1; */
      height: calc(100% - 12px);
      margin-right: 12px;
    }
  }
}

</style>
